//
//  String_public extension.swift
//  AJiTai
//
//  Created by BO ZHOU on 2020/5/30.
//  Copyright © 2020 BO ZHOU. All rights reserved.
//

import UIKit

public extension String {
    
    
    // 判断字符串中是否含有中文
    func isContainChinese() -> Bool {

        for (_, value) in self.enumerated() {

            if ("\u{4E00}" <= value  && value <= "\u{9FA5}") {
                return true
            }
        }

        return false
    }

    // 如果string含有中文或者特殊字符, 转码 (一般用于url)
    mutating func generateUrlMethod() {
        
        if self.isContainChinese() {
            let newUrl = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            self = newUrl
        }
    }
    
    /** 如果包含中文, 全部转码 (包括{} [] 等这种特殊字符 */
    var generateUrl: String {
        
        if self.isContainChinese() {
            let newUrl = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            return newUrl
        }
        return self
    }
    
    /** 强制转码 */
    var generateUrl_force: String {
        return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
    }

    /// url中含有中文和#的处理
    var validUrlString: String? {
        if let newString = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
            return newString.replacingOccurrences(of: "%23", with: "#")
        } else {
            return nil
        }
    }

    /// to UIImage
    var image: UIImage? {
        return UIImage(named: self)
    }
    
    var ns_string: NSString {
        return self as NSString
    }
    
    var doubleValue: Double {
        return ns_string.doubleValue
    }
    
    var intValue: Int {
        return ns_string.integerValue
    }
    
    
    var int32_Value: Int32 {
        return ns_string.intValue
    }
    
    var floatValue: Float {
        return ns_string.floatValue
    }
    
    var cgFloatValue: CGFloat {
        return CGFloat(floatValue)
    }
    
    
    /// writeTofile
    func write(toFile: String) {
        
        let directory = toFile.ns_string
        
        let d = directory.replacingOccurrences(of: directory.lastPathComponent, with: "")
        if !FileManager.default.fileExists(atPath: d) {
            try? FileManager.default.createDirectory(atPath: d, withIntermediateDirectories: true, attributes: nil)
        }
        
        try? self.write(toFile: toFile, atomically: true, encoding: .utf8)
    }
    

    static func convertDictionaryToJSONString(dict: NSDictionary?) -> Self {
        let data = try? JSONSerialization.data(withJSONObject: dict!, options: JSONSerialization.WritingOptions.init(rawValue: 0))
        let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        return jsonStr! as String
    }


    func convertToDictionary() -> [String: AnyObject]? {
        if let data = self.data(using: String.Encoding.utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.init(rawValue: 0)]) as? [String:AnyObject]
            } catch let error as NSError {
                 print(error)
            }
        }
        return nil
    }

}



// MARK: Rect

public extension String {
    
    /**
     * 根据height获取string能完全显示的宽度
     */
    func getwidth(font: UIFont, height: CGFloat) -> CGSize {
        let size = CGSize.init(width: CGFloat(MAXFLOAT), height: height)
        let dic = [NSAttributedString.Key.font: font] // swift 4.2
        let strSize = self.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context:nil).size
        return strSize
    }
    
    /**
     * 根据width获取string能完全显示的高度
     */
    func getHeight(font: UIFont, width: CGFloat) -> CGSize {
        let size = CGSize.init(width: width, height: CGFloat(MAXFLOAT))
        let dic = [NSAttributedString.Key.font: font] // swift 4.2
        let strSize = self.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context:nil).size
        return strSize
    }
}


// MARK: Range
public extension String {

    func ns_range(of subString: String) -> NSRange? {
        
        if let range = self.range(of: subString) {
            return NSRange(range, in: self)
        } else {
            return nil
        }
    }
}


// MARK: 时间

public extension String {

    func toDate(format: String) -> Date {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.date(from: self) ?? Date()
    }
    

//    func getDiyDateString(format: String) -> String {
//
//        let date = Date.dateFrom(format: format, formatString: self)
//        let currentDate = Date()
//
//        if Calendar.current.isDateInToday(date) {
//            // 今天
//            return "今天 \(date.getHour()!):" + "\(date.getMinute()!)"
//        } else if Calendar.current.isDateInYesterday(date) {
//            // 昨天
//            return "昨天 " + "\(date.getHour()!):" + "\(date.getMinute()!)"
//        } else if currentDate.year == date.year {
//
//            // 今年
//            return "\(date.month)-\(date.day) \(date.getHour()!):\(date.getMinute()!)"
//        } else {
//            // 非今年
//            return "\(date.year)-\(date.month)-\(date.day) \(date.getHour()!):\(date.getMinute()!)"
//        }
//    }
}


public extension NSString {
    
    
//    func getDiyDateString(format: String) -> String {
//        
//        let date = Date.dateFrom(format: format, formatString: self as String)
//        let currentDate = Date()
//        
//        if Calendar.current.isDateInToday(date) {
//            // 今天
//            return "今天 \(date.getHour()!):" + "\(date.getMinute()!)"
//        } else if Calendar.current.isDateInYesterday(date) {
//            // 昨天
//            return "昨天 " + "\(date.getHour()!):" + "\(date.getMinute()!)"
//        } else if currentDate.year == date.year {
//            
//            // 今年
//            return "\(date.month)-\(date.day) \(date.getHour()!):\(date.getMinute()!)"
//        } else {
//            // 非今年
//            return "\(date.year)-\(date.month)-\(date.day) \(date.getHour()!):\(date.getMinute()!)"
//        }
//    }
}
